<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\CommonManager;
use App\Http\Services\DomainManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\MerchantMedicine;
use App\OrderItem;
use App\Orders;
use App\PrescriptionDisease;
use App\PrescriptionInfo;
use App\SystemMedicine;
use App\User;
use App\UserCoupon;
use App\UserDrug;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Endroid\QrCode\QrCode;
use GuzzleHttp\Exception\GuzzleException;
use App\Message;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Intervention\Image\Facades\Image;

class PaymentController extends Controller
{
    public function weChatPayment(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereEnterpriseId($enterpriseId)
            ->whereOrderNum($orderNum)
            ->whereUserId($user->id)
            ->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->is_pay == 1)
            return response()->json(['level' => 'error','message' => '订单已支付']);

        if($thisOrder->status == 1 && (strtotime($thisOrder->created_at) + (30 * 60)) < time()){
            $thisOrder->status = 6;
            $thisOrder->save();
            return response()->json(['level' => 'error','message' => '订单已取消']);
        }

        $config = DomainManager::getPayConfig($request);
        if (!$config){
            \Log::notice('weChatPayment:$config=>'.var_dump($config));
            return response()->json(['level' => 'error','message' => '微信支付配置错误']);
        }
        if (!$config['app_id'] || !$config['mch_id'] || !$config['key'])
            return response()->json(['level'=>'error','message'=>'未配置微信支付信息']);

        $app = Factory::payment($config);
        try {
            $result = $app->order->unify([
                'body' => '商品购买',
                'out_trade_no' => $thisOrder->order_num,
                'total_fee' => (float)$thisOrder->pay_amount * 100,
                'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => route('Api.Payment.WeChatPayCallback'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $user->wx_openid,
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json(['level'=>'error','message'=>'InvalidArgumentException:'.$e->getMessage()]);
        } catch (InvalidConfigException $e) {
            return response()->json(['level'=>'error','message'=>'InvalidConfigException:'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level'=>'error','message'=>'GuzzleException:'.$e->getMessage()]);
        }


        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $prepayId = $result['prepay_id'];
            $json = $jssdk->bridgeConfig($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false

            return response()->json(['level' => 'success','message' => '支付订单创建成功','data'=>json_decode($json)]);
        }else{
            \Log::error('支付订单创建失败，错误信息：'.$result['return_msg']);
            return response()->json(['level' => 'error','message' => '支付订单创建失败','data' => $result]);
        }
    }

    /**
     * 获取支付二维码
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
     */
    public function getPayQrCode(Request $request){
        $codeUrl = !is_null($request->get('code_url')) ? $request->get('code_url') : '';

        $url = $codeUrl;
        $qrCode = new QrCode();
        $qrCode
            ->setText($url)
            ->setSize(250)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        $qrcodeContent = $qrCode->getImage();

        $qrcodeContentImg = Image::make($qrcodeContent);

        $response = response()->make($qrcodeContentImg->encode('png'));
        $response->header('Content-Type', 'image/png');

        return $response;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPayStatus(Request $request){
        $orderNum = !is_null($request->get('order_num')) ? $request->get('order_num') : '';
        $type     = !is_null($request->get('type')) ? $request->get('type') : 2;

        $order = Orders::whereOrderNum($orderNum)->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($type == 2){
            if($order->is_pay == 1){
                return response()->json(['level' => 'success','message' => '订单支付成功','data' => $order->is_pay]);
            }else{
                return response()->json(['level' => 'error','message' => '订单支付失败','data' => $order->is_pay]);
            }
        }elseif($type == 1){
            return response()->json(['level' => 'error','message' => '订单已取消']);
        }else{
            return response()->json(['level' => 'error','message' => '系统错误']);
        }

    }

    //微信支付回调
    public function WeChatPayCallback(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $config = DomainManager::getPayConfig($request);

        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            $ordersNum = $message['out_trade_no'];

            /** @var Orders $order */
            $order = Orders::whereOrderNum($ordersNum)->first();
            if (!$order || ($order && $order->is_pay == 1)) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    $userInfo = CommonManager::getUserBasicInfo($order->user_id);
                    $nickname = $userInfo ? $userInfo['nickname'] : '';

                    $newMessage = new Message();
                    $newMessage->user_id       = $order->user_id;
                    $newMessage->enterprise_id = $order->enterprise_id;
                    $newMessage->merchant_id   = $order->merchant_id;
                    $newMessage->order_num     = $order->order_num;
                    $newMessage->content       = $nickname . '有一个待发货的订单';
                    $newMessage->save();

                    $order->pay_time = date('Y-m-d H:i:s', time()); // 更新支付时间为当前时间
                    $order->pay_way = 'wechatpay';
                    $order->is_pay = 1;
                    $order->status = 2;
                    if ($order->delivery_method == 'self_pick')
                        $order->status=3;
                    $order->save(); // 保存订单

                    if($order->coupon_id != 0){
                        $userCoupon=UserCoupon::whereId($order->coupon_id)->whereIsUse(0)->first();
                        if($userCoupon){
                            $userCoupon->is_use=1;
                            $userCoupon->save();
                        }
                    }

                    if(!empty($order->prescription_info_id)){
                        try {
                            self::prescriptionHandle($order);
                        } catch (\Exception $e) {
                            Log::error("orderPrescriptionHandle：message=>" . $e->getMessage() . ",line=>" . $e->getLine());
                        }
                    }
//
                }
//                elseif ($message['result_code'] === 'FAIL') {
//                    //用户支付失败
//
//                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });
        return $response;
    }

    public static function prescriptionHandle(Orders $order = null){
        $prescriptionInfo = PrescriptionInfo::whereId($order->prescription_info_id)->whereHasPrescription(0)->where('perscriptionStatus',0)->first();
        if(!$prescriptionInfo)
            return false;

        $userDrug = UserDrug::whereId($prescriptionInfo->user_drug_id)->first();
        if(!$userDrug)
            return false;

        $medicineArr = [];
        $diseaseArr = [];
        $patientName = $userDrug->patientName;
        $patientSex = $userDrug->patientSex;
        $patientAge = $userDrug->patientAge;
        $patientWeight = $userDrug->patientWeight;
        $patientPhone = $userDrug->patientPhone;
        $patientIdcard = $userDrug->patientIdcard;
        $patientBirthday = date("Y-m-d",strtotime($userDrug->patientBirthday));
        $patientAddress = $userDrug->patientAddress;
        $diagnoseDescription = $prescriptionInfo->diagnoseDescription;
        $orderNum = $order->order_num;
        $pmh = $userDrug->pmh ?? '';
        $amh = $userDrug->amh ?? '';
        $fmh = $userDrug->fmh ?? '';
        $nurseDesc = $userDrug->nurse ?? '';
        $liverDesc = $userDrug->liver ?? '';
        $renalDesc = $userDrug->renal ?? '';
        $diagnosticLevel = $prescriptionInfo->diagnosticLevel;
        $drugUsage = $prescriptionInfo->drugUsage;

        $orderItemList = OrderItem::whereOrderId($order->id)->get();
        if(count($orderItemList) > 0){
            foreach ($orderItemList as $orderItem) {
                $medicine = MerchantMedicine::getMedicineDetailInfo($orderItem->merchant_medicine_id);
                if($medicine->drug_type == 1){
                    $sysMedicine = SystemMedicine::whereUpc($medicine->upc)->first();
                    if($sysMedicine){
                        $MedicineName = $sysMedicine->name;
                        $MedicineName = str_replace([$sysMedicine->drug_brand,$sysMedicine->specification],'',$MedicineName);
                        $MedicineName = trim($MedicineName);
                        $medicineItem = [
                            'drugName' => $MedicineName,
                            'spec' => $medicine->specification,
                            'approvalNumber' => $sysMedicine->approval_number,
                            'companyName' => $sysMedicine->manufacturer,
                            'Count' => $orderItem->num,
                            'countUnit' => $sysMedicine->packing,
                            'commonName' => $MedicineName
                        ];
                        array_push($medicineArr,$medicineItem);
                    }
                }
            }
        }

        $prescriptionDiseaseList = PrescriptionDisease::wherePrescriptionInfoId($prescriptionInfo->id)->get();
        if(count($prescriptionDiseaseList) > 0){
            foreach ($prescriptionDiseaseList as $prescriptionDisease) {
                $diseaseItem = [
                    'diseaseId' => $prescriptionDisease->disease_id,
                    'diseaseName' => $prescriptionDisease->disease_name
                ];

                array_push($diseaseArr,$diseaseItem);
            }
        }

        $drugstoreLoginInfo   = Redis::get('store_info');
        if(!$drugstoreLoginInfo){
            $drugstoreLoginInfo = self::drugstoreLogin();
            if(!$drugstoreLoginInfo){
                return false;
            }else{
                Redis::set('store_info',json_encode($drugstoreLoginInfo),'EX','3600');
            }
        }else{
            $drugstoreLoginInfo = json_decode($drugstoreLoginInfo);
        }

        $checkDoctorName = '张医师';
        $reviewDoctorName = '张医师';
        $arrangeDoctoreName = '李医师';
        $doctorList = self::getDoctorList();
        if(count($doctorList)  == 3){
            $checkDoctorName = $doctorList[0];
            $reviewDoctorName = $doctorList[1];
            $arrangeDoctoreName = $doctorList[2];
        }elseif(count($doctorList)  == 2){
            $checkDoctorName = $doctorList[0];
            $reviewDoctorName = $doctorList[0];
            $arrangeDoctoreName = $doctorList[1];
        }elseif(count($doctorList)  == 1){
            $checkDoctorName = $doctorList[0];
            $reviewDoctorName = $doctorList[0];
        }

        $data = [
            "appKey"=>"906917511",
            "drugStoreId" =>$drugstoreLoginInfo->id,
            "companyName" => $drugstoreLoginInfo->drugstoreName,
            "patientName"=>$patientName,
            "patientSex"=>$patientSex,
            "patientAge"=>$patientAge,
            "patientWeight"=>$patientWeight,
            "patientPhone"=>$patientPhone,
            "patientIdcard"=>$patientIdcard,
            "patientBirthday"=>$patientBirthday,
            "patientAddress"=>$patientAddress,
            "diagnoseDescription"=>$diagnoseDescription,
            "pmhType"=>$pmh ? 1 :0,
            "pmh"=>$pmh,
            "amhType"=>$amh ? 1 : 0,
            "amh"=>$amh,
            "fmhType"=>$fmh ? 1 : 0,
            "fmh"=>$fmh,
            "nurseType"=>$nurseDesc ? 1 : 0,
            "nurseDesc"=>$nurseDesc,
            "liverType"=>$liverDesc ? 1 : 0,
            "liverDesc"=>$liverDesc,
            "renalType"=>$renalDesc ? 1 : 0,
            "renalDesc"=>$renalDesc,
            "detailDiseaseList"=>json_encode($diseaseArr),
            "currentDetailDiseaseDesc"=>"",
            "detailDrugList"=>json_encode($medicineArr),
            "diagnosticLevel"=>$diagnosticLevel,
            "drugUsage"=>$drugUsage,
            "checkDoctorName"=>$checkDoctorName,
            "reviewDoctorName"=>$reviewDoctorName,
            "pageType"=>4,
            "enterpriseId"=>$order->enterprise_id,
            "arrangeDoctoreName"=>$arrangeDoctoreName,
            "outOrderId"=>$orderNum
        ];


        $result = self::prescriptionApplySubmit($data);
        $result = json_decode($result);
        if(!empty($result->code) && $result->code == 200){
            $prescriptionInfo->perscriptionNumber = $result->data;
            $prescriptionInfo->perscriptionStatus = 1;
            $prescriptionInfo->save();
            return $result->data;
        }else{
            $code = !empty($result->code) ? $result->code : '';
            $msg = !empty($result->msg) ? $result->msg : '';
            Log::error("prescriptionHandle：code=>$code,msg=>$msg");
            return '';
        }
    }

    public static function prescriptionApplySubmit($data)
    {
        $url = 'https://onlineprescription-api.yaojixin.com/prescriptionDetailInfo/commitPrescription';

        $drugstoreLoginInfo   = Redis::get('store_info');
        if(!$drugstoreLoginInfo){
            $drugstoreLoginInfo = self::drugstoreLogin();
            if(!$drugstoreLoginInfo){
                return false;
            }else{
                Redis::set('store_info',json_encode($drugstoreLoginInfo),'EX','3600');
            }
        }else{
            $drugstoreLoginInfo = json_decode($drugstoreLoginInfo);
        }

        $ch = curl_init();
        $header = array(
            "Authorization: $drugstoreLoginInfo->token",
            "clientType: store",
            "Content-Type: application/json"
        );

        $data = json_encode($data);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        try {
            $tmpInfo = curl_exec($ch);
        } catch (\Exception $e) {
            Log::error("prescriptionApplySubmit：message=>" . $e->getMessage());
            return null;
        }

        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        } else {
            curl_close($ch);
            return $tmpInfo;
        }
    }

    public static function drugstoreLogin(){
        $url = "https://onlineprescription-api.yaojixin.com/drugStore/storeLogin";

        $ch = curl_init();
        $header = array(
            "clientType: store",
            "Content-Type: application/json"
        );

        $data = [
            'registerPhone' => '18927587915',
            'registerPassword' => 'yqb1234',
            'loginType' => 1,
        ];

        $data = json_encode($data);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        try {
            $tmpInfo = curl_exec($ch);
        } catch (\Exception $e) {
            Log::error("drugstoreLogin：message=>" . $e->getMessage());
            return false;
        }
        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        } else {
            $tmpInfo = json_decode($tmpInfo);
            curl_close($ch);
            if(!empty($tmpInfo->code) && $tmpInfo->code == 200){
                return $tmpInfo->data;
            }else{
                $code = !empty($tmpInfo->code) ? $tmpInfo->code : '';
                $msg = !empty($tmpInfo->msg) ? $tmpInfo->msg : '';
                Log::error("drugstoreLogin：code=>$code,msg=>$msg");
                return false;
            }
        }
    }

    public static function getDoctorList(){
        $url = "https://onlineprescription-api.yaojixin.com/storeDoctor/getStoreDoctorList";

        $drugstoreLoginInfo   = Redis::get('store_info');
        if(!$drugstoreLoginInfo){
            $drugstoreLoginInfo = self::drugstoreLogin();
            if(!$drugstoreLoginInfo){
                return false;
            }else{
                Redis::set('store_info',json_encode($drugstoreLoginInfo),'EX','3600');
            }
        }else{
            $drugstoreLoginInfo = json_decode($drugstoreLoginInfo);
        }

        $header = array(
            "Authorization: $drugstoreLoginInfo->token",
            "clientType: store"
        );

        $data = [
            'storeId' => $drugstoreLoginInfo->id
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        try {
            $tmpInfo = curl_exec($ch);
        } catch (\Exception $e) {
            Log::error("getDoctorList：message=>" . $e->getMessage());
            return false;
        }
        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        } else {
            $tmpInfo = json_decode($tmpInfo);
            curl_close($ch);
            if(!empty($tmpInfo->code) && $tmpInfo->code == 200){
                $doctorNameArr = [];
                if(!empty($tmpInfo->data)){
                    foreach ($tmpInfo->data as $item) {
                        if(!empty($item->doctorName)){
                            array_push($doctorNameArr,$item->doctorName);
                        }
                    }
                }

                return $doctorNameArr;
            }else{
                $code = !empty($tmpInfo->code) ? $tmpInfo->code : '';
                $msg = !empty($tmpInfo->msg) ? $tmpInfo->msg : '';
                Log::error("getDoctorList：code=>$code,msg=>$msg");
                return false;
            }

        }
    }

    public static function getDrugListByTradeName($tradeName = '',$specification = ''){
        if(empty($tradeName) || empty($specification))
            return [];

        $url = "https://onlineprescription-api.yaojixin.com/drugInfo/getDrugSignByTradeName";

        $drugstoreLoginInfo   = Redis::get('store_info');
        if(!$drugstoreLoginInfo){
            $drugstoreLoginInfo = self::drugstoreLogin();
            if(!$drugstoreLoginInfo){
                return false;
            }else{
                Redis::set('store_info',json_encode($drugstoreLoginInfo),'EX','3600');
            }
        }else{
            $drugstoreLoginInfo = json_decode($drugstoreLoginInfo);
        }

        $header = array(
            "Authorization: $drugstoreLoginInfo->token",
            "clientType: store"
        );

        $data = [
            'tradeName' => $tradeName,
            'specification' => $specification,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        try{
            $tmpInfo = curl_exec($ch);
        } catch (\Exception $e) {
            Log::error("getDrugListByTradeName：message=>" . $e->getMessage());
            return [];
        }

        if (curl_errno($ch)) {
            curl_close($ch);
            return [];
        } else {
            $tmpInfo = json_decode($tmpInfo);
            curl_close($ch);
            if(!empty($tmpInfo->code) && $tmpInfo->code == 200){
                $diseaseInfoVOList = [];
                if(!empty($tmpInfo->data->diseaseInfoVOList)){
                    foreach ($tmpInfo->data->diseaseInfoVOList as $item) {
                        $val = ['id' => $item->id,'name' => $item->icdName];

                        array_push($diseaseInfoVOList,$val);
                    }
                }

                return $diseaseInfoVOList;
            }else{
                $code = !empty($tmpInfo->code) ? $tmpInfo->code : '';
                $msg = !empty($tmpInfo->msg) ? $tmpInfo->msg : '';
                Log::error("getDrugListByTradeName：code=>$code,msg=>$msg");
                return [];
            }
        }
    }

    public static function getAllDiseaseList($icName = '',$page = 1,$limit = 10){
        if(empty($icName) || empty($page) || empty($limit))
            return [];

        $url = "https://onlineprescription-api.yaojixin.com/diseaseInfo/getDiseaseInfoPageList";

        $drugstoreLoginInfo   = Redis::get('store_info');
        if(!$drugstoreLoginInfo){
            $drugstoreLoginInfo = self::drugstoreLogin();
            if(!$drugstoreLoginInfo){
                return false;
            }else{
                Redis::set('store_info',json_encode($drugstoreLoginInfo),'EX','3600');
            }
        }else{
            $drugstoreLoginInfo = json_decode($drugstoreLoginInfo);
        }

        $header = array(
            "Authorization: $drugstoreLoginInfo->token",
            "clientType: store"
        );

        $data = [
            'icdName' => $icName,
            'pageNum' => $page,
            'pageSize' => $limit,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        try{
            $tmpInfo = curl_exec($ch);
        } catch (\Exception $e) {
            Log::error("getAllDiseaseList：message=>" . $e->getMessage());
            return [];
        }

        if (curl_errno($ch)) {
            curl_close($ch);
            return [];
        } else {
            $tmpInfo = json_decode($tmpInfo);
            curl_close($ch);
            if(!empty($tmpInfo->code) && $tmpInfo->code == 200){
                $diseaseInfoVOList = [];
                if(!empty($tmpInfo->data->list)){
                    foreach ($tmpInfo->data->list as $item) {
                        $val = ['id' => $item->id,'name' => $item->icdName];

                        array_push($diseaseInfoVOList,$val);
                    }
                }

                return $diseaseInfoVOList;
            }else{
                $code = !empty($tmpInfo->code) ? $tmpInfo->code : '';
                $msg = !empty($tmpInfo->msg) ? $tmpInfo->msg : '';
                Log::error("getDrugListByTradeName：code=>$code,msg=>$msg");
                return [];
            }
        }
    }

    /**
     * 退款接口（订单不可为空）
     * @param Orders $thisOrder
     * @param $reason
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function Refund(Orders $thisOrder,$reason,$refundAmount,$refundNum){
        $config = DomainManager::getUnPayConfig($thisOrder);
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($thisOrder->order_num, $refundNum, $thisOrder->pay_amount * 100, $refundAmount * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => $reason,
        ]);

        return $result;
    }

    /**
     * 退款查询接口（订单不可为空）
     * @param Orders $thisOrder
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function selectRefund(Orders $thisOrder = null,$refundOrderNum = ''){
        $config = DomainManager::getUnPayConfig($thisOrder);
        $app = Factory::payment($config);
        $result = $app->refund->queryByOutRefundNumber($refundOrderNum);
        return $result;
    }
}
